//
//  SearchViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/9/23.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "SearchViewController.h"
#import "RecommendTableViewCell.h"
#import "MallProductDetailViewController.h"
#import "HotelTableViewCell.h"
#import "SearchTableViewCell.h"
#import "SSKeychain.h"
#import "ComboViewController.h"
#import "HotelViewController.h"
@interface SearchViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)NSMutableArray * cellArr;
@property (nonatomic, assign)int currentPage;
@property (nonatomic, strong)UIView * navBG;//搜索栏背景
@property (nonatomic, strong)UITextField * searchTextField;//搜索栏
@property (nonatomic, strong)NSString * searchString;//搜索内容

- (NSString *)getDeviceUUID;
@end

@implementation SearchViewController(networking)
- (void)getSearchData{
    NSDictionary * dic = @{
                           @"goodsname":self.searchString,
                           @"only":[self getDeviceUUID]
                           };
    [[AFAppDotNetAPIClient sharedClient] POST:@"indexiosApi/search" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self.cellArr removeAllObjects];
            if ([responseObject[@"list"][@"conditiongoods"] count] > 0) {
                [self.cellArr addObjectsFromArray:responseObject[@"list"][@"conditiongoods"]];
            }
            [self.tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end
@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.delegate = self;
    [self setStatusBarBackgroundColor:[UIColor clearColor]];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.currentPage = 1;
    [self.view addSubview:self.navBG];
    [self.view addSubview:self.tableView];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isHomePage animated:YES];
}
- (UIView *)navBG{
    if (!_navBG) {
        _navBG = [[UIView alloc] init];
        if (Is_Iphone_X) {
            _navBG.frame = CGRectMake(0, 40/WIDTH_6_SCALE, SCREEN_WIDTH, 44/WIDTH_6_SCALE);
        }else{
            _navBG.frame = CGRectMake(0, 20/WIDTH_6_SCALE, SCREEN_WIDTH, 44/WIDTH_6_SCALE);
        }
        _navBG.backgroundColor = [UIColor whiteColor];
        //后退
        UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 0, 25/WIDTH_6_SCALE, 25/WIDTH_6_SCALE)];
        backBtn.centerY = _navBG.height/2;
        [backBtn setBackgroundColor:[UIColor clearColor]];
        [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_navBG addSubview:backBtn];
        //搜索背景
        UIView * searchBGView = [[UIView alloc] initWithFrame:CGRectMake(backBtn.right + 10/WIDTH_6_SCALE, 0, SCREEN_WIDTH - backBtn.right - 10/WIDTH_6_SCALE - 20/WIDTH_6_SCALE, 28/WIDTH_6_SCALE)];
        searchBGView.centerY = backBtn.centerY;
        searchBGView.backgroundColor = [UIColor clearColor];
        searchBGView.layer.borderColor = getColor(@"221815").CGColor;
        searchBGView.layer.borderWidth = 1;
        searchBGView.layer.cornerRadius = 12;
        searchBGView.layer.masksToBounds = YES;
        [_navBG addSubview:searchBGView];
        //搜索栏
        self.searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(5/WIDTH_6_SCALE, 1/WIDTH_6_SCALE, searchBGView.width - 10/WIDTH_6_SCALE, searchBGView.height - 2/WIDTH_6_SCALE)];
        UIImageView *searchImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 14/WIDTH_6_SCALE, 14/WIDTH_6_SCALE)];
        searchImage.image = [UIImage imageNamed:@"magnifyingGlass"];
        self.searchTextField.leftView = searchImage;
        self.searchTextField.leftViewMode = UITextFieldViewModeAlways;
        self.searchTextField.delegate = self;
        self.searchTextField.font = DEF_FontSize_12;
        self.searchTextField.layer.borderColor = getColor(mainColor).CGColor;
        self.searchTextField.layer.borderWidth = 1;
        [self.searchTextField addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
        [searchBGView addSubview:self.searchTextField];
    }return _navBG;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navBG.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - self.navBG.height - self.navBG.top) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[RecommendTableViewCell class] forCellReuseIdentifier:NSStringFromClass([RecommendTableViewCell class])];
        [_tableView registerClass:[HotelTableViewCell class] forCellReuseIdentifier:NSStringFromClass([HotelTableViewCell class])];
        _tableView.backgroundColor = getColor(mainColor);
    }return _tableView;
}
- (NSMutableArray *)cellArr{
    if (!_cellArr) {
        _cellArr = @[].mutableCopy;
    }return _cellArr;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = nil;
    if ([[self.cellArr[indexPath.row] objectForKey:@"typeid_goods"] isEqualToString:@"1"]) {
        RecommendTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([RecommendTableViewCell class]) forIndexPath:indexPath];
        cell.model = self.cellArr[indexPath.row];
        return cell;
    }else{
        HotelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HotelTableViewCell class]) forIndexPath:indexPath];
        cell.model = self.cellArr[indexPath.row];
        return cell;
    }return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[self.cellArr[indexPath.row] objectForKey:@"typeid_goods"] isEqualToString:@"1"]) {
        MallProductDetailViewController * vc = [[MallProductDetailViewController alloc] init];
        vc.produceID = [self.cellArr[indexPath.row] objectForKey:@"goodsid"];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        HotelViewController * vc = [[HotelViewController alloc] init];
        vc.prodeceID = [self.cellArr[indexPath.row] objectForKey:@"typeid_goods"];
        vc.navigationItem.title = [self.cellArr[indexPath.row] objectForKey:@"name"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[self.cellArr[indexPath.row] objectForKey:@"typeid_goods"] isEqualToString:@"1"]) {
        return 150/WIDTH_6_SCALE;
    }else{
        return 121/WIDTH_6_SCALE;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellArr.count;
}
#pragma mark - textFieldDelegate
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    self.searchString = string;
//    [self getSearchData];
//    return YES;
//}
- (void)textFieldDidChange{
    self.searchString = self.searchTextField.text;
    [self getSearchData];
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 获取唯一标识符
- (NSString *)getDeviceUUID{
    NSString * currentDeviceUUIDStr = [SSKeychain passwordForService:@"com.liqiu"account:@"uuid"];
    if (currentDeviceUUIDStr == nil || [currentDeviceUUIDStr isEqualToString:@""])
    {
        NSUUID * currentDeviceUUID  = [UIDevice currentDevice].identifierForVendor;
        currentDeviceUUIDStr = currentDeviceUUID.UUIDString;
        currentDeviceUUIDStr = [currentDeviceUUIDStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
        currentDeviceUUIDStr = [currentDeviceUUIDStr lowercaseString];
        [SSKeychain setPassword: currentDeviceUUIDStr forService:@"com.liqiu"account:@"uuid"];
    }return currentDeviceUUIDStr;
}
@end
